//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2006-2007
//
// Debug traces support.
//

# include "StdAfx.h"
# include "Trace.h"

static
void _TraceImpl (const char * _strFmt, va_list _vl) {
	char strTime [16];
	::sprintf (strTime, "%04u: ", ::GetTickCount () % 10000UL);
	::OutputDebugString (strTime);

	char strBuf [MAX_PATH*2];
	::_vsnprintf (strBuf, sizeof (strBuf)/sizeof (strBuf [0]), _strFmt, _vl);

	::OutputDebugString (strBuf);
	if (_strFmt [::strlen (_strFmt) - 1] != '\n')
		::OutputDebugString ("\n");
}

void __cdecl Trace (const char * _strFmt, ...) {
	va_list vl;
	va_start (vl, _strFmt);

	_TraceImpl (_strFmt, vl);

	va_end (vl);
}

void __cdecl TraceC (bool _bCond, const char * _strFmt, ...) {
	if (! _bCond)
		return;

	va_list vl;
	va_start (vl, _strFmt);

	_TraceImpl (_strFmt, vl);

	va_end (vl);
}

void TraceLastError (const char * _strComment) {
# ifdef _DEBUG
	const DWORD dwError = ::GetLastError ();

	char * pMsgBuf = NULL;
	::FormatMessage (
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		dwError,
		MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
		reinterpret_cast<LPTSTR> (& pMsgBuf),
		0, NULL
	);
	if (! pMsgBuf)
		return;

	if (_strComment)
		TRACE ("%s - Error %d: %s", _strComment, dwError, pMsgBuf);
	else
		TRACE ("Error %d: %s", dwError, pMsgBuf);

	::LocalFree (pMsgBuf);
# endif // _DEBUG
}
